package com.share.beta.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.share.common.common.LoginInfo;
import com.share.common.common.LoginInfoContext;
import com.share.common.common.Result;
import com.share.common.enums.ErrMsgEnum;
import com.share.config.redis.RedisTokenManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTokenManager redisTokenManager;

    /*前端首页--url*/
    @Value("${frontLoginUrl:undefine}")
    private String frontLoginUrl;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse rsp, Object handler) throws Exception {
        String realRequestUrl = getRealRequestUrl(req);

        //2.从header中取token
        String token = req.getHeader("token");
        LoginInfo login = redisTokenManager.getUserInfo(token, LoginInfo.class);
        try {
            if (login == null) {
                log.error("token为空");
                redirectLogin(req, rsp);//去登陆页面
                return false;
            }

            LoginInfoContext.setSession(login);//绑定到当前线程
            return true;
        } catch (Exception e) {
            log.error("token提取异常", e);
            redirectLogin(req, rsp);//去登陆页面
            return false;
        }
    }


    public String getRealRequestUrl(HttpServletRequest req) {
        String requestURI = req.getRequestURI();
        String realRequestUrl = null;
        String contextPath = req.getContextPath();
        if ("".equals(contextPath) || "/".equals(contextPath)) {
            realRequestUrl = requestURI;
        } else {
            realRequestUrl = requestURI.substring(contextPath.length());
        }
        return realRequestUrl;
    }

    // 对于请求是ajax请求重定向问题的处理方法
    public void redirectLogin(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
        rsp.setHeader("Pragma", "No-cache");
        rsp.setHeader("Cache-Control", "no-cache");
        rsp.setContentType("application/json;charset=utf-8");
        try {
            Object redirectUrl = frontLoginUrl;
//            String redirectUrl = getJdLoginUrl();
            log.info("请求的url=" + req.getRequestURL());
            String remoteIp = StringUtils.isEmpty(req.getHeader("X-Forwarded-For")) ? req.getRemoteAddr() : req.getHeader("X-Forwarded-For");
            log.info("源请求host=" + remoteIp + ",port=" + req.getServerPort());
            log.error("登录拦截器--->该用户未登陆!!!,前端要跳转登录redirectUrl=" + redirectUrl);
            Result result = Result.failure(ErrMsgEnum.loginInfoMissErr, redirectUrl);//这个参数有重载--所以不能乱定义数据类型
            rsp.getOutputStream().write(JSONObject.toJSONString(result).getBytes("utf-8"));
            rsp.getOutputStream().close();
        } catch (IOException e) {
            log.error(e.getLocalizedMessage(), e);
        }
    }
}
